package com.fs.sys.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fs.common.bean.UserContextHolder;
import com.fs.sys.bean.dto.TenantDTO;
import com.fs.sys.bean.dto.TenantUserDTO;
import com.fs.sys.bean.dto.UserDTO;
import com.fs.sys.bean.query.TenantUserQuery;
import com.fs.sys.service.TenantUserService;
import com.fs.sys.entityservice.TenantEntityService;
import com.fs.sys.entityservice.TenantUserEntityService;
import com.fs.sys.entityservice.UserEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 租户用户关系控制器 
 * @author Coder Generator 2025-06-13 21:09:55 
 **/
@RestController
@RequestMapping("/sys/tenant-user")
@Slf4j
@Tag(name = "租户用户关系控制器")
public class TenantUserController {
    @Autowired
    private TenantUserEntityService service;

    @Autowired
    private UserEntityService userEntityService;

    @Autowired
    private TenantEntityService tenantEntityService;

    @Autowired
    private TenantUserService tenantUserService;

    @PostMapping("page-query")
    @Operation(summary = "查询-分页")
    public IPage<UserDTO> pageQuery(@RequestBody TenantUserQuery query) {
        IPage<TenantUserDTO> pageData = service.pageQuery(query);
        List<TenantUserDTO> list = pageData.getRecords();
        Map<String, UserDTO> userMap;
        if (!CollectionUtils.isEmpty(list)) {
            List<String> userIds = list.stream().map(TenantUserDTO::getUserId).toList();
             userMap = userEntityService.findByIds(userIds)
                    .stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        } else {
            userMap = new HashMap<>(15);
        }
        return pageData.convert(item -> userMap.get(item.getUserId()));
    }

    /**
     * 查询当前用户的租户列表
     * @return 当前用户租户列表
     */
    @GetMapping("user-tenants")
    public List<TenantDTO> userTenants() {
        String userId = UserContextHolder.getUserIdOrThrow();
        return tenantUserService.userTenants(userId);
    }

    /**
     * 租户切换
     * @param tenantId 租户id
     */
    @GetMapping("switch-tenant")
    public void switchTenant(String tenantId) {
        String userId = UserContextHolder.getUserIdOrThrow();
        tenantUserService.switchTenant(tenantId, userId);
    }
}